# -*- coding:utf-8 -*-
# 该文件是db的__init__.py实现
import warnings

from django.core import signals
from django.db.utils import (DEFAULT_DB_ALIAS,
    DataError, OperationalError, IntegrityError, InternalError,
    ProgrammingError, NotSupportedError, DatabaseError,
    InterfaceError, Error,
    load_backend, ConnectionHandler, ConnectionRouter)
from django.utils.functional import cached_property

# 表明该package中包含的元素，模块内可以直接使用
__all__ = ('backend', 'connection', 'connections', 'router', 'DatabaseError',
    'IntegrityError', 'DEFAULT_DB_ALIAS')


# connections和router存放的数据类型不是一样的。
# 在__init__.py中实现一些初始化工作，达到直接通过包import调用的效果
connections = ConnectionHandler()                   # 初始化，建立与mysql的连接

# 当多数据库的情况下，django使用router指定sql执行的是哪个库，有时候也用作读写分离的操作
# 实现分数据库，只需要一个实现db_for_read, db_for_write等函数的类就可以了
# 产生一个connectionRouter的实例
router = ConnectionRouter()                         # 与mysql连接的路由，

# `connection`, `DatabaseError` and `IntegrityError` are convenient aliases
# for backend bits.

# DatabaseWrapper.__init__() takes a dictionary, not a settings module, so
# we manually create the dictionary from the settings, passing only the
# settings that the database backends care about. Note that TIME_ZONE is used
# by the PostgreSQL backends.
# We load all these up for backwards compatibility, you should use
# connections['default'] instead.
class DefaultConnectionProxy(object):
    """
    Proxy for accessing the default DatabaseWrapper object's attributes. If you
    need to access the DatabaseWrapper object itself, use
    connections[DEFAULT_DB_ALIAS] instead.
    """
    def __getattr__(self, item):
        return getattr(connections[DEFAULT_DB_ALIAS], item)

    def __setattr__(self, name, value):
        return setattr(connections[DEFAULT_DB_ALIAS], name, value)

    def __delattr__(self, name):
        return delattr(connections[DEFAULT_DB_ALIAS], name)

connection = DefaultConnectionProxy()

class DefaultBackendProxy(object):
    """
    Temporary proxy class used during deprecation period of the `backend` module
    variable.
    """
    @cached_property
    def _backend(self):
        warnings.warn("Accessing django.db.backend is deprecated.",
            PendingDeprecationWarning, stacklevel=2)
        return load_backend(connections[DEFAULT_DB_ALIAS].settings_dict['ENGINE'])

    def __getattr__(self, item):
        return getattr(self._backend, item)

    def __setattr__(self, name, value):
        return setattr(self._backend, name, value)

    def __delattr__(self, name):
        return delattr(self._backend, name)

backend = DefaultBackendProxy()

# 断开连接，该方法目前已经不建议使用
def close_connection(**kwargs):
    warnings.warn(
        "close_connection is superseded by close_old_connections.",
        PendingDeprecationWarning, stacklevel=2)                    # 提示该接口已经被close_old_connections取代
    # Avoid circular imports
    from django.db import transaction
    for conn in connections:
        # If an error happens here the connection will be left in broken
        # state. Once a good db connection is again available, the
        # connection state will be cleaned up.
        transaction.abort(conn)
        connections[conn].close()                           # 断开连接

# Register an event to reset saved queries when a Django request is started.
# 重置查询缓存
def reset_queries(**kwargs):
    for conn in connections.all():
        conn.queries = []
signals.request_started.connect(reset_queries)

# Register an event to reset transaction state and close connections past
# their lifetime. NB: abort() doesn't do anything outside of a transaction.
# 该方法仅request和response的信号机制下被触发执行
def close_old_connections(**kwargs):
    for conn in connections.all():
        # Remove this when the legacy transaction management goes away.移除goes away的连接管理
        try:
            conn.abort()
        except DatabaseError:
            pass
        conn.close_if_unusable_or_obsolete()            # 如果不可用、废弃就关闭该连接
signals.request_started.connect(close_old_connections)                  # 绑定close_old_connections接收者到request_started的singal实例
signals.request_finished.connect(close_old_connections)                 # close_old_connections绑定到实例，作为信号的接收者
